//
//  NSDate+Extension.swift
//  SinaWeiBo
//
//  Created by ZKJ on 2017/9/11.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import Foundation

extension Date {
    static func createDateString(creatDate : String) -> String {
        
        //1.创建时间格式化对象
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "tianniuge")
        
        // 2.将字符串时间,转成NSDate类型
        guard let creatDate = fmt.date(from: creatDate) else {
            return ""
        }
        
        // 3.当前时间
        let nowDate = Date()
        
        // 4.计算创建时间和当前时间的时间差
        let interval = Int(nowDate.timeIntervalSince(creatDate))
        
        // 5.对时间间隔处理
        // 5.1.显示刚刚
        if interval < 60 {
            return "刚刚"
        }
        
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        
        if interval < 60 * 60 * 24 {
            return "\(interval / (60 * 60))小时前"
        }
        
        // 5.4.创建日历对象
        let calender = Calendar.current
        
        // 5.5.处理昨天数据: 昨天 12:23
        if calender.isDateInYesterday(creatDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: creatDate)
            return timeStr
        }
        
        // 5.6.处理一年之内: 02-22 12:22
        let cmps = (calender as NSCalendar).components(.year, from: creatDate, to: nowDate, options: [])
        if cmps.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: creatDate)
            return timeStr
        }
        
        // 5.7.超过一年: 2014-02-12 13:22
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: creatDate)
        return timeStr
    }
}




